/*
 * udiskinterface.cpp - Udisks dBus interface - emit mount device
 *
 * Copyright (C) 2010-2012 Serge Begger
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "udiskinterface.h"

udiskInterface::udiskInterface(QObject *parent) :
    QObject(parent)
{
    filter << "*.aac" << "*.mp3" << "*.flac" << "*.ape" << "*.ogg"
            << "*.ogm" << "*.ogv" << "*.mp4"  << "*.avi" << "*.ts"
            << "*.wv"  << "*.3gp" << "*.m2ts" << "*.vob" << "*.wmv"
            << "*.wav" << "*.mpg" << "*.mov"  << "*.m4a" << "*.m4v"
            << "*.mka" << "*.mkv" << "*.mpc";

    QDBusConnection::systemBus().connect(
                            "org.freedesktop.UDisks",
                            "/org/freedesktop/UDisks",
                            "org.freedesktop.UDisks",
                            "DeviceAdded",this,SLOT(deviceAdded(QDBusObjectPath)));
}

int udiskInterface::findMultimedia(QString filepath, int counter)
{
    QDir d(filepath);
    QStringList files = d.entryList(filter, QDir::Files, QDir::Name);
    if (files.count()) {
        counter = counter + 1;
    }

    QStringList dirs = d.entryList(QDir::Dirs, QDir::Name);
    foreach (QString str, dirs) {
        if (str != "." && str != "..")
            counter = counter + findMultimedia(filepath+"/"+str,0);
    }

    return counter;
}

void udiskInterface::volumeMount()
{
    QString mountPoint = device->property("DeviceMountPaths").toString();
    if (findMultimedia( mountPoint, 0) > 0) {
        myMessage message(0);
        message.exec(3,"Mounted device: find multimedia files. Play it?");
        if (message.result) {
            emit volumeAdded(mountPoint);
        }
    }
}


void udiskInterface::deviceAdded(QDBusObjectPath ObjectPath)
{
    device = new QDBusInterface("org.freedesktop.UDisks",ObjectPath.path(),"org.freedesktop.UDisks.Device",QDBusConnection::systemBus(),this);
    int partNum = device->property("PartitionNumber").toInt();
    if (partNum) {
        sleep(1); //???FIXME
        if (device->property("DeviceIsMounted").toBool()) {
            volumeMount();
        }
    }
}

